<!DOCTYPE HTML>
<html>
<head>
    <title>动画 - 震动</title>
    <meta charset="utf-8">
    <script language="javascript" type="text/javascript" src="./jQuery/jquery-1.7.1.js"></script>
    <link href="./CSS/canvas.css" rel="stylesheet" type="text/css">
</head>
<script type="text/javascript">
    var Shape = function(x,y,width,heigth){
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = heigth;

        this.radius = Math.random()*30;
        this.angle = 0;
    }
</script>
<body>
    <canvas id="myCanvas" height="500" width="500"></canvas>
    <div>
        <button id="startAnimation">Start</button>
        <button id="stopAnimation">Stop</button>
    </div>
</body>
<script type="text/javascript">
    var canvas = $("#myCanvas");
    context = canvas.get(0).getContext("2d");

    canvasWidth = canvas.width();
    canvasHeight = canvas.height();

    var playAnimation = true;

    var startButtion = $("#startAnimation");
    var stopButtion = $("#stopAnimation");

    stopButtion.hide();
    startButtion.click(function()
    {
        $(this).hide();
        stopButtion.show();
        playAnimation = true;
        animate();
    });
    stopButtion.click(function()
    {
        $(this).hide();
        startButtion.show();
        playAnimation = false;
    });

    var x = 0;
    var shapeArray = new Array();
    for(var  i = 0;i < 10 ; i++  )
    {
        var x = 500*Math.random();
        var y = 500*Math.random();
        var width = height = 20*Math.random();
        shapeArray.push(new Shape(x,y,width,height));
    }

    function animate()
    {
        if(playAnimation)
        {
            context.clearRect(0,0,canvasWidth,canvasHeight);
            var arrayLength = shapeArray.length;
            for(var i = 0;i < arrayLength; i ++)
            {
                var tmpShape = shapeArray[i];
//                tmpShape.x +=Math.random()*4 - 2;
//                tmpShape.y +=Math.random()*4 - 2;
                var x = tmpShape.x + tmpShape.radius*Math.sin(tmpShape.angle*(Math.PI/180));
                var y = tmpShape.y + tmpShape.radius*Math.cos(tmpShape.angle*(Math.PI/180));
                tmpShape.angle += 5;
                context.fillStyle = "red";
                context.fillRect(x,y,tmpShape.width,tmpShape.height);

            }

            setTimeout(animate,33);
        }

    }
//    alert(canvas.height());

</script>
</html>